import React, { Component } from "react";
import { Tabs, Form, Input, Select, Space, Button, Modal, message, Checkbox, InputNumber, Radio, Image } from "antd"
import GoBack from "@/components/TheGoBack";
import TheButton from "@/components/TheButton";
import TheUpload from "@/components/TheUpload";
import TheCascader from "./TheCascader.jsx"
import Calendar from "./calendar"
import Table from "./table"
import TheTags from "./TheTags"
import "../style.scss";
import { apiAddService, apiServiceDetail, apiEditService } from "@/request/callServicer/serveList";
const { Option } = Select

export default class Add extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef
    this.state = {
      dateList: null,
      priceArr0: {},
      priceArr1: {},
      priceArr2: {},
      citys: [],//遍历城市的标签  修改时展示用
      city: [],
      mhcCustomAdvanceDTOList: [],
      setMhcCustomAdvanceDTOList: [],
      multiplePetsPrice: 0.00,
      type: '',
      showTypes: '',
      vacationAdvancePrice: 0,
      mhcServiceAreaDTOList: [],
      specsFormList: [],
      resourceTypeList: [
        { label: "喂养", value: 'FEED' },
        { label: "洗护", value: 'CARE' },
      ],
      skuArr: [
        // {
        //   name: "宠物分类",
        //   // children: ["猫猫", "狗狗", "有猫有狗"],
        //   children: [],
        //   display: true,
        //   uploadFLag: false,
        //   detailImg: "",
        // },
      ],
      skuArr0: [],
      skuArr1: [],
      skuArr2: [],
      titleArr0: [],
      titleArr1: [],
      titleArr2: [],

      specsFormList0: [],
      specsFormList1: [],
      specsFormList2: [],

      tabArr: [],
      distanceArr: [],
      radioValue: "",//节假日加价
    }
  }
  componentDidMount() {
    const { type, id } = this.props.match.params
    this.setState({ type: type, id: id, }, () => {
      if (id) {
        this.getView(id)
      }
    })
  }
  // 资源位详情
  async getView(mhcServiceId) {
    let res = await apiServiceDetail({ mhcServiceId })
    if (res.code === 0) {
      let { vacationAdvancePrice, mhcServiceAreaDTOList, type, distanceAdvancePriceList, multiplePetsPrice, vacationAdvanceType, mhcCustomAdvanceDTOList } = res.data
      let citys = []
      //城市
      let city = mhcServiceAreaDTOList.map(item => {
        // citys.push(item[["province", "city", "district"][item.areaLevel - 1]])
        let arr = []
        let cityItem = {}
        let ci = ""
        for (let index = 0; index < item.areaLevel; index++) {
          ci += item[["province", "city", "district"][index]]
          arr.push(item[["provinceId", "cityId", "districtId"][index]])
          if (index == 0) {
            cityItem['label'] = item.province
            cityItem['value'] = item.provinceId
          }
        }
        citys.push(ci)
        return arr
      })
      let specsJson = { specsJson0: [], specsJson1: [], specsJson2: [] }
      const tabArr = { 'FEED': ["猫猫", "狗狗", "有猫有狗"], 'CARE': ["猫猫", "狗狗"] }[type]
      for (let i = 0; i < tabArr.length; i++) {
        //sku规格
        specsJson["specsJson" + i] = res.data[["specsCatJsonList", "specsDogJsonList", "specsDogAndCatJsonList"][i]].map((item, index) => {
          return {
            name: item.specsKeyName,
            display: index === 0,
            uploadFLag: item.specsKeyImage !== null,
            detailImg: item.specsKeyImage !== null ? [{
              uid: '-1',
              name: 'image.png',
              url: item.specsKeyImage,
            }] : [],
            children: item.values.map(it => {
              return it.specsValue
            })
          }
        })
      }
      //sku规格
      // let skuArr = specsJson.map((item, index) => {
      //   return {
      //     name: item.specsKeyName,
      //     display: index === 0,
      //     uploadFLag: item.specsKeyImage !== null,
      //     detailImg: item.specsKeyImage !== null ? [{
      //       uid: '-1',
      //       name: 'image.png',
      //       url: item.specsKeyImage,
      //     }] : [],
      //     children: item.values.map(it => {
      //       return it.specsValue
      //     })
      //   }
      // })
      // skuArr[0].children = { 'FEED': ["猫猫", "狗狗", "有猫有狗"], 'CARE': ["猫猫", "狗狗"] }[type]

      //表格价格
      let priceArr = []
      for (let i = 0; i < tabArr.length; i++) {
        let priceItem = {}
        res.data[["specsCatFormList", "specsDogFormList", "specsDogAndCatFormList"][i]].map(item => {
          let uuid = ""
          //json字符串转成数组   因为直接转为对象下标会改变
          item.slice(1, -1).split(',').map((it, ix) => {
            let chatArr = it.replace(/\"/g, "").split(":")
            if (chatArr.length === 2 && !["预计消耗", "价格", "id"].includes(chatArr[0])) {
              uuid += ix === 0 ? '' : ':'
              uuid += chatArr[0] + ":" + chatArr[1]
            }
          })
          let items = JSON.parse(item)
          priceItem[uuid + ':price'] = React.$transNum(items['价格'], 2, -2)
          priceItem[uuid + ':expend'] = items['预计消耗']
          priceItem[uuid + ':id'] = items['id']
        })
        priceArr.push(priceItem)
      }
      // specsFormList.map(item => {
      //   let uuid = ""
      //   let items = JSON.parse(item)
      //   Object.keys(items).map((it, idx) => {
      //     if (!["预计消耗", "价格", "id"].includes(it)) {
      //       uuid += idx > 0 ? ':' : '';
      //       uuid += it + ":" + items[it]
      //     }
      //   })
      //   priceArr[uuid + ':price'] = React.$transNum(items['价格'], 2, -2)
      //   priceArr[uuid + ':expend'] = items['预计消耗']
      //   priceArr[uuid + ':id'] = items['id']
      // })
      let dateList = {}
      mhcCustomAdvanceDTOList.map(item => {
        dateList[item.advanceTime] = React.$transNum(item.advancePrice, 2, -2)
      })
      let ds = distanceAdvancePriceList.map(item => {
        item.advancePrice = React.$transNum(item.advancePrice, 2, -2)
        return item
      })

      this.formRef.setFieldsValue({ type: type })
      //规格类型
      this.setState({
        vacationAdvancePrice: vacationAdvancePrice ? React.$transNum(vacationAdvancePrice, 2, -2) : 0,
        dateList,
        radioValue: parseInt(vacationAdvanceType),
        multiplePetsPrice: React.$transNum(multiplePetsPrice, 2, -2),
        distanceArr: ds,
        priceArr0: priceArr[0],
        priceArr1: priceArr[1],
        mhcServiceAreaDTOList,
        tabArr,
        skuArr0: specsJson["specsJson0"],
        skuArr1: specsJson["specsJson1"],
        showTypes: res.data.type,
        city,
        citys,//用在遍历城市标签
      })
      if (tabArr.length === 3) {
        this.setState({
          skuArr2: specsJson["specsJson2"],
          priceArr2: priceArr[2],

        })
      }
    }
  }

  // 资源位list数据
  resourceTypeData() {
    this.setState({
      resourceTypeList: [
        { label: "喂养", value: "FEED" },
        { label: "洗护", value: "CARE" },
      ],
    })
  }
  message = (content) => {
    React.$message({
      type: 'error',
      content
    })
    this.setState({ saveFormBtn: false })
  }
  // 保存form表单
  onFinish = async (insertType) => {
    const { mhcCustomAdvanceDTOList, skuArr, mhcServiceAreaDTOList, specsFormList, multiplePetsPrice, radioValue, distanceArr, vacationAdvancePrice, tabArr } = this.state
    const type = this.formRef.getFieldValue('type')
    if (!type) return this.message('请选择服务类型')
    if (!mhcServiceAreaDTOList.length) return this.message('请设置可服务的地区')
    if (radioValue === "") return this.message('请设置节假日加价')
    this.setState({ saveFormBtn: true })
    let specsJson = {
      specsCatJsonList: [],
      specsDogJsonList: [],
      specsDogAndCatJsonList: [],
    }
    for (let i = 0; i < tabArr.length; i++) {
      try {
        specsJson[["specsCatJsonList", "specsDogJsonList", "specsDogAndCatJsonList"][i]] = this.state["skuArr" + i].map(item => {
          if (!item.name) {
            throw new Error("请输入规格类型");
          }
          if (item.children.length <= 0) {
            throw new Error("请至少添加1个规格值");
          }
          let param = {
            specsKeyName: item.name,
            values: item.children.map(item => {
              return { specsValue: item }
            })
          }
          if (item.uploadFLag) {
            if (item.detailImg.length == 0) {
              throw new Error("请上传图片说明");
            }
            param['specsKeyImage'] = item.detailImg[0].url
          }
          return param
        })
      } catch (error) {
        this.message(error.toString())
        return
      }
    }

    let specsList = {
      specsDogAndCatFormList: [],
      specsCatFormList: [],
      specsDogFormList: []
    }
    for (let i = 0; i < tabArr.length; i++) {
      try {
        //返回原有的sku  id
        specsList[["specsCatFormList", "specsDogFormList", "specsDogAndCatFormList"][i]] = this.state["specsFormList" + i].map(items => {
          console.log("items", items);
          let item = Object.assign({}, items)
          if (isNaN(item['价格']) || !(item['价格'])) {
            throw new Error('基础价格信息不能为空')
          }
          item['价格'] = React.$transNum(item['价格'], 0, 2)
          let priceArr = this.state["priceArr" + i]
          let arr = []
          Object.getOwnPropertyNames(priceArr).map(item => {
            if (item.includes(":id")) {
              arr.push(item.split(":id")[0])
            }
          })
          let it = Object.assign({}, item)
          delete it['价格']
          delete it['预计消耗']
          let uuid = ""
          Object.keys(it).map((its, idx) => {
            uuid += idx > 0 ? ':' : '';
            uuid += its + ":" + it[its]
          })
          if (arr.includes(uuid)) {
            item["id"] = this.state["priceArr" + i][uuid + ':id']
          }
          return JSON.stringify(item).replaceAll('title:', '')
        })
      } catch (error) {
        this.setState({ saveFormBtn: false })
        return React.$message({
          type: 'error',
          content: error + ''
        })
      }
    }

    let distanceAdvancePriceList = distanceArr.map(item => {
      let advancePrice = React.$transNum(item.advancePrice, 0, 2)
      return { ...item, advancePrice }
    })
    let params = {
      vacationAdvanceType: radioValue,
      type,
      mhcCustomAdvanceDTOList,
      distanceAdvancePriceList,
      multiplePetsPrice: React.$transNum(multiplePetsPrice, 0, 2),
      mhcServiceAreaDTOList,
      insertType,
      specsCatJsonList: specsJson["specsCatJsonList"],
      specsDogJsonList: specsJson["specsDogJsonList"],
      specsCatFormList: specsList["specsCatFormList"],
      specsDogFormList: specsList["specsDogFormList"],
    }
    if (radioValue === 1) {
      params["vacationAdvancePrice"] = React.$transNum(vacationAdvancePrice, 0, 2)
    }
    if (tabArr.length > 2) {
      params["specsDogAndCatJsonList"] = specsJson["specsDogAndCatJsonList"]
      params["specsDogAndCatFormList"] = specsList["specsDogAndCatFormList"]
    }
    if (this.state.id) {
      params["mhcServiceId"] = this.state.id
      let res = await apiEditService({ ...params })
      if (res.code === 0) {
        message.success('修改成功！')
        this.props.history.go(-1)
      }
    } else {
      let res = await apiAddService({ ...params })
      if (res.code === 0) {
        if (insertType == 'Y') {
          message.success('保存成功')
        } else if (insertType == 'N') {
          message.success('上架成功')
        }
        this.props.history.go(-1)
      }
    }
    this.setState({ saveFormBtn: false })
  }
  addSku = (idx) => {
    let skuArr = this.state["skuArr" + idx]

    skuArr.push({
      name: "",
      detailImg: [],
      children: [],
      uploadFLag: false,
    })
    this.setState({
      ["skuArr" + idx]: skuArr
    })
  }
  deleteSku = (idx, i) => {
    const func = () => {
      const sku = this.state["skuArr" + i]
      const skuDel = sku.filter((_, index) => {
        return index !== idx
      })

      this.setState({
        ["skuArr" + i]: [...skuDel],
      })
    }
    if (this.state.id) {
      React.$confirm({
        title: "提示",
        type: 'warning',
        content: "删除规格类型后，对应的规格值和已创建的基础价格信息都会被删除，是否继续操作？",
        onOk: async () => {
          func()
        },
      });
    } else {
      func()
    }

  }
  getFileResult(value, idx, index) {
    let skuArr = this.state["skuArr" + index]
    if (value.length && value[0] && value[0].response) {
      skuArr[idx].detailImg = [{
        uid: '-1',
        name: 'image.png',
        url: value[0].response.data
      }]
    } else {
      skuArr[idx].detailImg = []
    }
    this.setState({
      ["skuArr" + index]: skuArr
    })
  }

  UpdateTag = (params, idx, i) => {
    let arr = this.state["skuArr" + i]
    this.setState({
      ["skuArr" + i]: arr.map((item, index) => idx === index ? { ...item, children: params } : item)
    })
  }
  onChangeType = (val, idx, index) => {
    let skuArr = this.state['skuArr' + index]
    skuArr[idx].name = val.target.value.replace(' ', '')
    this.setState({
      ['skuArr' + index]: skuArr
    })
  }
  showImage = (params, idx, index) => {
    let skuArr = this.state['skuArr' + index]
    skuArr[idx].uploadFLag = params.target.checked
    this.setState({
      ['skuArr' + index]: skuArr
    })
  }
  addDistanceArr = () => {
    let distanceArr = this.state.distanceArr
    distanceArr.push({
      minDistance: 0,
      maxDistance: 0,
      advancePrice: 0
    })
    this.setState({
      distanceArr
    })
  }
  deleteDistanceArr = (idx) => {
    const func = () => {
      let distanceArr = this.state.distanceArr
      distanceArr.splice(idx, 1)
      this.setState({
        distanceArr
      })
    }
    if (this.state.id) {
      React.$confirm({
        title: "提示",
        type: 'warning',
        content: "删除条目后，可能会影响正在下单的用户，是否继续操作？",
        onOk: async () => {
          func()
        },
      });
    } else {
      func()
    }

  }
  radio = (params) => {
    this.setState({
      radioValue: params.target.value
    })
  }
  getResourceType = (params) => {
    const mhcServiceAreaDTOList = params.map(item => {
      return {
        province: item.length > 0 ? item[0].label : "",
        provinceId: item.length > 0 ? item[0].value : "",
        city: item.length > 1 ? item[1].label : "",
        cityId: item.length > 1 ? item[1].value : "",
        district: item.length > 2 ? item[2].label : "",
        districtId: item.length > 2 ? item[2].value : "",
        areaLevel: item.length
      }
    })
    this.setState({
      mhcServiceAreaDTOList
    })
  }
  getSpecsFormList = (params, i) => {
    this.setState({
      ["specsFormList" + i]: params,
    })
  }
  setDistance = (params, key, idx) => {
    let distanceArr = this.state.distanceArr
    distanceArr[idx][key] = params
    this.setState({
      distanceArr
    })
  }
  setMultiplePetsPrice = (params) => {
    this.setState({
      multiplePetsPrice: params
    })
  }
  showTypes = (params) => {
    const arr = { 'FEED': ["猫猫", "狗狗", "有猫有狗"], 'CARE': ["猫猫", "狗狗"] }[params]
    arr.map((item, i) => {
      this.setState({
        ["skuArr" + i]: [
          {
            name: "宠物分类",
            children: [item],
            display: true,
            uploadFLag: false,
            detailImg: "",
          },
        ],
      })
    })
    this.setState({
      tabArr: arr,
      showTypes: params
    })
  }
  setVacationAdvancePrice = (params) => {
    this.setState({
      vacationAdvancePrice: params
    })
  }
  setMhcCustomAdvanceDTOList = (params) => {
    let list = []
    Object.keys(params).map(item => {
      if (params[item] !== 0) {
        list.push({
          advanceTime: item,
          advancePrice: React.$transNum(params[item], 0, 2)
        })
      }
    })
    this.setState({
      mhcCustomAdvanceDTOList: list
    })
  }
  formatter = (params) => {
    if (!params) return
    if (params % 1 == 0) {
      params = parseInt(params)
    }
    return params
  }
  //获取当前日期函数
  getNowFormatDate() {
    let date = new Date(),
      year = date.getFullYear(), //获取完整的年份(4位)
      month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
      strDate = date.getDate() // 获取当前日(1-31)
    if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0  
    if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
    return `${year}-${month}-${strDate}`
  }

  onChangeTab = (key) => {
    console.log(key);
  };

  render() {
    const { skuArr0, tabArr, dateList, multiplePetsPrice, priceArr, citys, city, vacationAdvancePrice, showTypes, type, distanceArr, resourceTypeList, skuArr, isModalOpen, detailImg, saveFormBtn, radioValue } = this.state
    return (
      <div className='p-layout-box'>
        <GoBack
          history={this.props.history}
          title={{ add: '新增', detail: '查看详情', edit: '修改' }[type]}
        />
        <div className="p-layout-content" style={{ marginTop: '30px' }}>
          <Form
            name="form"
            labelCol={{ span: 2, }}
            wrapperCol={{ span: 10, }}
            onFinish={this.onFinish}
            ref={ref => this.formRef = ref}
          >
            <Form.Item
              label="服务类型"
              name="type"
            >
              <Select placeholder="请选择服务类型" onChange={this.showTypes} disabled={type == 'detail'}>
                {resourceTypeList.map(item => <Option value={item.value} >{item.label}</Option>)}
              </Select>
            </Form.Item>
            <Form.Item
              label="可服务地区"
            >
              <TheCascader citys={city} onChange={this.getResourceType} disabled={type == 'detail'} />
            </Form.Item>
            {tabArr.length > 0 && <div>
              <Form.Item
                label="规格类型"
                name="resourceType"
              >
                <div className="a_border">
                  <Tabs
                    onChange={this.onChangeTab}
                    type="card"
                    items={tabArr.map((name, i) => {
                      const id = String(i + 1);
                      return {
                        label: name,
                        key: id,
                        children: <>
                          {this.state["skuArr" + i].length < 10 &&
                            <TheButton type="primary" onClick={() => this.addSku(i)} style={{ marginBottom: '10px' }} disabled={type == 'detail'}>新增类型</TheButton>
                          }
                          {this.state["skuArr" + i].length > 0 && this.state["skuArr" + i].map((item, index) => {
                            return index !== 0 ? (
                              <div>
                                <div className="a_tr" >
                                  <div>规格类型:</div>
                                  <Input placeholder="规格类型" style={{ width: '150px', marginRight: '15px' }} maxLength={10} value={item.name} onChange={e => this.onChangeType(e, index, i)} disabled={type === 'detail' || item.display} />
                                  <div className="a_tr">
                                    <Checkbox checked={item.uploadFLag} onChange={e => this.showImage(e, index, i)} disabled={type == 'detail'} />
                                    <div style={{ width: '150px', margin: '0 15px' }}>图片说明</div>
                                    <TheUpload key={JSON.stringify(item.detailImg)} className="add_upload" getFileResult={(value) => this.getFileResult(value, index, i)} maxSize={5} fileList={[...item.detailImg]} len={1} disabled={type == 'detail'} />
                                    <TheButton className="deleteBtn" onClick={() => this.deleteSku(index, i)} disabled={type == 'detail'}>删除</TheButton>
                                  </div>
                                </div>
                                <div style={{ padding: '10px', display: 'flex' }}>
                                  规格值：<TheTags tags={item.children} index={index} updateItem={e => this.UpdateTag(e, index, i)} type={type} />
                                </div>
                              </div>
                            ) : <></>
                          })}
                        </>,
                      };
                    })}
                  />
                </div>
              </Form.Item>

              <Form.Item
                label="基础价格信息"
                name="resourceName"
              >
              </Form.Item>
              {tabArr.map((_, i) => {
                return (
                  <div style={{ margin: '20px 0 20px 100px', }} >
                    <Table arr={this.state["skuArr" + i]} tabIndex={i} priceArr={this.state["priceArr" + i]} getData={this.getSpecsFormList} disabled={type == 'detail'} />
                  </div>
                )
              })}
            </div>}
            <div className="title">附加价格规则</div>
            <div className="bottomBg">
              <Form.Item
                label="距离加价"
                name="resourceName"
              >
              </Form.Item>
              <div style={{ transform: 'translateY(-30px)', }}>
                <div className="tableTitle">
                  <div style={{ width: '420px', }}>距离范围</div>
                  <div>加价(元）</div>
                  {type !== 'detail' && <div style={{ marginLeft: '180px' }}>操作</div>}
                </div>
                {distanceArr.map((item, idx) =>
                  <div className="distance_item">
                    <InputNumber value={item.minDistance} style={{ width: '100px' }} precision={0} onChange={(e) => this.setDistance(e, 'minDistance', idx)} disabled={type == 'detail'} />  <div style={{ width: '110px' }}>公里(包含)  ~</div>
                    <InputNumber value={item.maxDistance} style={{ width: '100px' }} precision={0} onChange={(e) => this.setDistance(e, 'maxDistance', idx)} disabled={type == 'detail'} />
                    <div>公里(不包含)</div>
                    <InputNumber value={item.advancePrice} style={{ width: '100px' }} precision={2} formatter={this.formatter} onChange={(e) => this.setDistance(e, 'advancePrice', idx)} disabled={type == 'detail'} />
                    {type !== 'detail' && <TheButton onClick={() => this.deleteDistanceArr(idx)} style={{ marginLeft: '140px' }} >删除</TheButton>
                    }                  </div>
                )}
                {type !== 'detail' && <div className="addItem">
                  <TheButton onClick={this.addDistanceArr}>新增条目</TheButton>
                </div>}
              </div>
              {
                showTypes == 'FEED' && <Form.Item
                  label="多宠加价"
                  name="multiplePetsPrice"
                >
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ width: '110px' }}>每增加1只，加价</div><InputNumber formatter={this.formatter} precision={2} value={multiplePetsPrice} style={{ width: '150px' }} onChange={this.setMultiplePetsPrice} /><div>元</div>
                  </div>
                </Form.Item>}
              <Form.Item
                label="节假日加价"
              >
                <Radio.Group onChange={this.radio} value={radioValue} disabled={type == 'detail'}>
                  <Space direction="vertical">
                    <Radio value={1}>法定节假日，单次加价
                      <InputNumber disabled={type == 'detail'} precision={2} formatter={this.formatter}
                        onChange={this.setVacationAdvancePrice} value={vacationAdvancePrice} style={{ width: '100px' }} /></Radio>
                    <Radio value={2}>自定义单次加价</Radio>
                  </Space>
                </Radio.Group>
              </Form.Item>
              <div style={{ height: '700px' }}>
                {(dateList || type == 'add') &&
                  <Calendar data={dateList} disableDateStr={this.getNowFormatDate()} getData={this.setMhcCustomAdvanceDTOList} disabled={type == 'detail'} />
                }              </div>
            </div>
          </Form>
          {type !== 'detail' && <Space className="bottomBtn"  >
            <Button onClick={() => this.props.history.goBack()}>取消</Button>
            <Button htmlType="submit" type="primary" loading={saveFormBtn} onClick={() => this.onFinish("N")}>保存并下架</Button>
            <Button htmlType="submit" type="primary" loading={saveFormBtn} onClick={() => this.onFinish("Y")}>保存并上架</Button>
          </Space>}
          <Modal title="选择频道" visible={isModalOpen} onOk={isModalOpen} width={1200}
            onCancel={this.cancelChannel}>
          </Modal>
        </div >
      </div >
    )
  }
}
